package com.itheima.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.CheckGroupDao;
import com.itheima.health.dao.CheckItemDao;
import com.itheima.health.dao.SetMealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.CheckGroupService;
import com.itheima.health.service.CheckItemService;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangmeng
 * @description 套餐SEVICE实现类
 * @date 2019/9/26
 **/
@Service
@Slf4j
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private SetMealDao setMealDao;

    @Autowired
    private CheckGroupDao checkGroupDao;

    @Autowired
    private CheckItemDao checkItemDao;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        log.info("[套餐-添加]data:{},checkgroupIds:{}",setmeal,checkgroupIds);
        // 调用DAO数据入库
        // 插入基本数据
        setMealDao.insert(setmeal);
        // 插入关联数据
        for (Integer checkgroupId : checkgroupIds) {
            setMealDao.insertSetMealAndCheckGroup(setmeal.getId(),checkgroupId);
        }

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //DAO查询数据
        Page<Setmeal> page = setMealDao.selectByCondition(queryPageBean.getQueryString());
        //封装返回值
        return new PageResult(page.getTotal(),page.getResult());
    }

    //根据id查询套餐
    @Override
    public Setmeal findById(Integer id) {
        //根据id查询导出
        Setmeal setmeal = setMealDao.findById(id);

        //根据套餐id查询检查组
        List<CheckGroup> checkGroups = checkGroupDao.findCheckGroupsBySetMealId(setmeal.getId());

        //遍历检查组
        for (CheckGroup checkGroup : checkGroups) {
            //根据每个检查组id查询检查项
            List<CheckItem> checkItems = checkItemDao.findCheckItemsByCheckGroupId(checkGroup.getId());
            //将获取的检查项添加到检查组
            checkGroup.setCheckItems(checkItems);
        }

        //将获取的检查组添加到套餐
        setmeal.setCheckGroups(checkGroups);

        return setmeal;
    }

    @Override
    public Integer selectCountByImgName(String imgName) {
        //根据图片名称查询
        Integer count=setMealDao.selectByImgName(imgName);
        return count;
    }
}
